package com.issac.service.serviceImpl;

import cn.hutool.core.map.MapUtil;
import com.issac.common.Const;
import com.issac.common.R;
import com.issac.service.CaptchaService;
import com.issac.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;
import com.google.code.kaptcha.Producer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName CaptchaServiceImpl
 * @Author zy
 * @Date 2022/6/22 9:42
 * @Description CaptchaServiceImpl
 * @Version 1.0
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private Producer producer;

    @Override
    public R getCaptcha() throws IOException {
        // 生成验证码
        String code = producer.createText();
        // 键
        String key = UUID.randomUUID().toString();
        // 生成验证码图片
        BufferedImage image = producer.createImage(code);
        // 将图片写入流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        // 对图片编码
        String base64Img = str + encoder.encode(outputStream.toByteArray());

        // 存储到redis中
        redisUtil.hset(Const.KAPTCHA_KEY, key, code, 120);

        // 将键和图片返回至前端
        Map<Object, Object> build = MapUtil.builder()
                .put("key", key)
                .put("captchaImg", base64Img)
                .build();
        R ok = R.ok(build);

        return ok;
    }
}
